<?php

namespace Ladenise\EveStationTradingBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\Tools\Pagination\Paginator;
use PHPEveCentral\PHPEveCentral;
use Ladenise\EveStationTradingBundle\Entity\MarketStatRequest;
use Ladenise\EveStationTradingBundle\Entity\MarketStatRequestInvtype;
use Ladenise\EveStationTradingBundle\Entity\MarketStatResponse;

class EveCentralImportCommand extends ContainerAwareCommand {

    protected function configure() {
        $this
                ->setName('eve:eve-central-import')
                ->setDescription('Import data from Eve Central')
                ->addArgument('soloarsystemid', InputArgument::OPTIONAL, 'Where do you want to import stat from?', 30002053)
                ->addArgument('typeid', InputArgument::IS_ARRAY, 'What do you want to import?')
//            ->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
//        $name = $input->getArgument('name');
//        $input->getOption('yell')
//        $output->writeln($text);

        $batchSize = 20;

        $entityManagerEve = $this->getContainer()->get('doctrine')->getEntityManager();
        $entityManagerEveStationTrading = $this->getContainer()->get('doctrine')->getEntityManager('eve_station_trading');

        $connection = $entityManagerEveStationTrading->getConnection();
        $platform = $connection->getDatabasePlatform();

        $connection->executeUpdate($platform->getTruncateTableSQL('est_market_stat_response', true /* whether to cascade */));
        $connection->executeUpdate($platform->getTruncateTableSQL('est_market_stat_request_invtype', true /* whether to cascade */));
        $connection->executeUpdate($platform->getTruncateTableSQL('est_market_stat_request', true /* whether to cascade */));

        $qb = $entityManagerEve->createQueryBuilder()
                ->select('count(t.id)')
                ->from('LadeniseEveBundle:Invtypes', 't')
                ->where('t.marketgroupid IS NOT NULL');

        $countInvTypes = $qb->getQuery()->getSingleScalarResult();

        $limit = 100;
        $loops = ceil($countInvTypes / $limit);
        $output->writeln($loops . ' tours');

        $hours = null;
        $solarSystemId = $input->getArgument('soloarsystemid');
        $minimumQuantity = null;

        $marketStatRequest = new MarketStatRequest();
        $marketStatRequest->setSolarsystemid($solarSystemId);
        $marketStatRequest->setHours($hours);
        $marketStatRequest->setMinimumQuantity($minimumQuantity);

        $entityManagerEveStationTrading->persist($marketStatRequest);

        $dql = "SELECT t FROM LadeniseEveBundle:Invtypes t WHERE t.marketgroupid IS NOT NULL";

        for ($i = 0; $i < $loops; $i++) {

            $output->writeln('tour ' . $i);

            $firstResult = $i * $limit;

            $query = $entityManagerEve->createQuery($dql)
                    ->setFirstResult($firstResult)
                    ->setMaxResults($limit);

            $entities = new Paginator($query, false);

            $queryEveCentral = PHPEveCentral::getInstance()->MarketStat()
                    ->setHours($hours)
                    ->setMinimumQuantity($minimumQuantity)
                    ->setUseSystem($solarSystemId);

            $j = 0;
            $invTypes = array();

            foreach ($entities as $type) {
                $j++;

                $queryEveCentral->addTypeId($type->getId());

                $marketStatRequestInvtype = new MarketStatRequestInvtype();
                $marketStatRequestInvtype->setMarketstatrequest($marketStatRequest);
                $marketStatRequestInvtype->setTypeid($type->getId());

                $entityManagerEveStationTrading->persist($marketStatRequestInvtype);

                $invTypes[$type->getId()] = $marketStatRequestInvtype;

                if (($j % $batchSize) == 0) {
                    $entityManagerEveStationTrading->flush();
                }
            }

            $results = $queryEveCentral->send();

            $j = 0;

            foreach ($results->getAllTypes() as $typeid => $result) {
                $j++;

                $grossMargin = $result->sell->min - $result->buy->max;
                $taxesFees = (($result->sell->min + $result->buy->max) / 2) * 0.0225;
                $netMargin = $grossMargin - $taxesFees;
                if ($result->sell->min > 0) {
                    $marginPercentage = ($netMargin / $result->sell->min) * 100;
                } else {
                    $marginPercentage = 0;
                }

                $marketStatResponse = new MarketStatResponse();
                $marketStatResponse->setMarketStatRequestInvtype($invTypes[$typeid]);
                $marketStatResponse->setSellVolume($result->sell->volume);
                $marketStatResponse->setSellAvg($result->sell->avg);
                $marketStatResponse->setSellMax($result->sell->max);
                $marketStatResponse->setSellMin($result->sell->min);
                $marketStatResponse->setSellStddev($result->sell->stddev);
                $marketStatResponse->setSellMedian($result->sell->median);
                $marketStatResponse->setSellPercentile($result->sell->percentile);
                $marketStatResponse->setBuyVolume($result->buy->volume);
                $marketStatResponse->setBuyAvg($result->buy->avg);
                $marketStatResponse->setBuyMax($result->buy->max);
                $marketStatResponse->setBuyMin($result->buy->min);
                $marketStatResponse->setBuyStddev($result->buy->stddev);
                $marketStatResponse->setBuyMedian($result->buy->median);
                $marketStatResponse->setBuyPercentile($result->buy->percentile);
                $marketStatResponse->setAllVolume($result->all->volume);
                $marketStatResponse->setAllAvg($result->all->avg);
                $marketStatResponse->setAllMax($result->all->max);
                $marketStatResponse->setAllMin($result->all->min);
                $marketStatResponse->setAllStddev($result->all->stddev);
                $marketStatResponse->setAllMedian($result->all->median);
                $marketStatResponse->setAllPercentile($result->all->percentile);
                $marketStatResponse->setGrossMargin($grossMargin);
                $marketStatResponse->setTaxesFees($taxesFees);
                $marketStatResponse->setNetMargin($netMargin);
                $marketStatResponse->setNetMarginPercentage($marginPercentage);

                $entityManagerEveStationTrading->persist($marketStatResponse);

                if (($j % $batchSize) == 0) {
                    $entityManagerEveStationTrading->flush();
                }
            }

            $entityManagerEveStationTrading->clear(); // Detaches all objects from Doctrine!
        }
    }

}